package com.vimi8.app.framework.net

import android.app.AlertDialog
import android.content.Context
import android.widget.Toast
import okhttp3.Request
import okhttp3.ResponseBody
import org.json.JSONObject
import java.io.IOException
import java.io.InterruptedIOException
import java.net.MalformedURLException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * Created by xuybin on 2017/8/15.
 */
data class HttpError(var code: Int, var error: String, var errorDescription: String, var raw: String = "", var url: String = "未知", var method: String = "") : Throwable() {
    fun showDialog(context: Context, title: String = "", content: String = "") {
        try {
            when {
                this.code in 200..299 || this.code in 490..499 || this.code == 404 || this.code == 401 || this.code == 502 -> {
                    val normalDialog = AlertDialog.Builder(context)
                    normalDialog.setTitle(this.error)
                    normalDialog.setMessage(this.errorDescription);
                    normalDialog.setPositiveButton("确定") { dialog, _ ->
                        dialog.dismiss()
                    }
                    normalDialog.show()
                }
                title.isNotEmpty() && content.isNotEmpty() -> {
                    val normalDialog = AlertDialog.Builder(context)
                    normalDialog.setTitle(title)
                    normalDialog.setMessage(content);
                    normalDialog.setPositiveButton("确定") { dialog, _ ->
                        dialog.dismiss()
                    }
                    normalDialog.show()
                }
                this.code in 400..489 -> {
                    val normalDialog = AlertDialog.Builder(context)
                    normalDialog.setTitle("请求失败")
                    normalDialog.setMessage("请求失败,请检查后重试!");
                    normalDialog.setPositiveButton("确定") { dialog, _ ->
                        dialog.dismiss()
                    }
                    normalDialog.show()
                }
                this.code > 500 -> {
                    val normalDialog = AlertDialog.Builder(context)
                    normalDialog.setTitle("请求异常")
                    normalDialog.setMessage("请求异常,请稍后再试!");
                    normalDialog.setPositiveButton("确定") { dialog, _ ->
                        dialog.dismiss()
                    }
                    normalDialog.show()
                }
            }
        } catch (ex: Exception) {

        }
    }

    fun showToast(context: Context, content: String = "") {
        try {
            when {
                this.code in 200..299 || this.code in 490..499 || this.code == 404 || this.code == 401 || this.code == 502 -> Toast.makeText(context, this.errorDescription, Toast.LENGTH_LONG)
                content.isNotEmpty() -> Toast.makeText(context, content, Toast.LENGTH_LONG)
                this.code in 400..489 -> Toast.makeText(context, "请求失败,请检查后重试!", Toast.LENGTH_LONG)
                this.code > 500 -> Toast.makeText(context, "请求异常,请稍后再试!", Toast.LENGTH_LONG)
            }
        } catch (ex: Exception) {

        }
    }

    companion object {
        fun newInstance(code: Int, request: Request, responseBody: ResponseBody?): HttpError {
            var httpError = HttpError(code, "异常错误", "异常错误,已经上报管理员")
            try {
                httpError.url = request.url().toString();
                httpError.method = request.method().toUpperCase()
                when (httpError.code) {
                    401 -> {
                        httpError.error = "无权限访问"
                        httpError.errorDescription = "未登录或无此权限,请登录后重试!"
                    }
                    404 -> {
                        httpError.error = "服务未找到"
                        httpError.errorDescription = "服务器未找到,请检查!"
                    }
                    502 -> {
                        httpError.error = "服务离线"
                        httpError.errorDescription = "服务器在维护,请稍后再试!"
                    }
                    else -> {
                        val data = responseBody?.string()
                        if (data != null) {
                            try {
                                val jsonObject = JSONObject(data)
                                if (jsonObject.optString("error", "").isNotEmpty()) {
                                    httpError.error = jsonObject.optString("error", "")
                                }
                                if (jsonObject.optString("errorDescription", "").isNotEmpty()) {
                                    httpError.errorDescription = jsonObject.optString("errorDescription", "")
                                } else if (jsonObject.optString("error_description", "").isNotEmpty()) {
                                    var error_description = jsonObject.optString("error_description", "")
                                    if (error_description.indexOf("error=\"") > 0 && error_description.indexOf("\", error_description=\"") > 0) {
                                        var error = error_description.substring(error_description.indexOf("error=\"") + 7, error_description.indexOf("\", error_description=\""))
                                        error_description = error_description.substring(error_description.indexOf("\", error_description=\"") + 22, error_description.length - 1)
                                        httpError.error = error
                                    }
                                    httpError.errorDescription = error_description
                                }
                            } catch (ex: Exception) {
                                //忽略异常
                            } finally {
                                httpError.raw = if (data.length > 1024) data.substring(0, 1024) else data
                            }
                        }
                    }
                }
            } catch (ex: Exception) {
                httpError.raw = ex.message ?: ""
            } finally {
                return httpError
            }
        }

        fun newInstance(ex: Throwable): HttpError {
            var httpError = HttpError(490, "异常错误", "异常错误,已经上报管理员")
            try {
                when (ex) {
                    is UnknownHostException -> {
                        httpError.code = 499
                        httpError.error = "无法访问网络"
                        httpError.errorDescription = "无法访问网络,请连4G或wifi网络!"
                    }
                    is MalformedURLException -> {
                        httpError.code = 498
                        httpError.error = "URL格式错误"
                        httpError.errorDescription = "请检查URL格式是否正确!"
                    }
                    is InterruptedIOException -> {
                        httpError.code = 497
                        httpError.error = "请求被中断"
                        httpError.errorDescription = "请检查,是否强制终端了网络!"
                    }
                    is SocketTimeoutException -> {
                        httpError.code = 496
                        httpError.error = "网络不稳定"
                        httpError.errorDescription = "网络不稳定,请检查网络!"
                    }
                    is IOException -> {
                        httpError.code = 495
                        httpError.error = "网络不稳定"
                        httpError.errorDescription = "网络不稳定,请检查网络!"
                    }
                    else -> {
                        httpError.code = 490
                        httpError.error = "异常错误"
                        httpError.errorDescription = "异常错误,已经上报管理员!"
                    }
                }
            } catch (ex: Exception) {
                //忽略异常
            } finally {
                return httpError
            }
        }
    }
}